package net.xdclass.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.swing.*;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
    @Bean("threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //线程池创建的核⼼线程数，线程池维护线程的最少数量,即使没有任务需要执⾏，也会⼀直存活
        //如果设置allowCoreThreadTimeout=true（默认false）时，核⼼线程会超时关闭
        executor.setCorePoolSize(16);
        //最⼤线程池数量，当线程数>=corePoolSize，且任务队列已满时。线程池会创建新线程来处理任务
        //当线程数=maxPoolSize，且任务队列已满时，线程池会拒绝处理任务⽽抛出异常
        executor.setMaxPoolSize(64);
        //缓存队列（阻塞队列）当核⼼线程数达到最⼤时，新任务会放在队列中排队等待执⾏
        executor.setQueueCapacity(1024);
        //当线程空闲时间达到keepAliveTime时，线程会退出，直到线程数量=corePoolSize
        //允许线程空闲时间30秒，当maxPoolSize的线程在空闲时间到达的时候销毁
        //如果allowCoreThreadTimeout=true，则会直到线程数量=0
        executor.setKeepAliveSeconds(30);
       //spring 提供的 ThreadPoolTaskExecutor 线程池，是有setThreadNamePrefix() ⽅法的。
       // jdk 提供的ThreadPoolExecutor 线程池是没有setThreadNamePrefix() ⽅法的
        executor.setThreadNamePrefix("⼩滴课堂Spring⾃带Async前缀：");

        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //初始化线程池
        executor.initialize();

        return executor;
    }
}
